<?php

namespace backend\services\config;

use backend\extensions\ApiBaseService;
use backend\models\config\AdminUser;
use backend\services\captcha\CaptchaService;
use backend\services\config\MenuService;
use backend\models\config\AdminRole;
use backend\models\config\AdminMenu;

/**
 * Desc 管理员服务类
 * @author HUI
 */
class AdminService extends ApiBaseService
{

    /**
     * 登录
     * @param array $params 参数 
     * * */
    public static function login($params)
    {
        if (CaptchaService::validateCode($params) == false) {
            return self::jsonError('验证码异常,请检查');
        }
        $admin = AdminUser::getDataOne(['account' => $params['account']]);
        if (empty($admin)) {
            return self::jsonError('账号异常，请检查');
        }
        if ($admin['pass'] != md5(trim($params['pass']))) {
            return self::jsonError('密码异常，请检查');
        }
        $token = md5($params['account'] . $admin['pass']);
        $data = [
            'token' => $token,
            'name' => $admin['name']
        ];
        // 获取权限
        \common\services\cache\CommonCache::setCache($token, $admin);
        return self::jsonSuccess($data);
    }

    /**
     * 退出登录
     * @param array $params 参数 
     * * */
    public static function logout() {
        $headers = \Yii::$app->getRequest()->getHeaders();
        \common\services\cache\CommonCache::clearCache($headers->get('token'));
        return self::jsonSuccess();
    }

    /**
     * 获取授权菜单
     * * */
    public static function getMenu()
    {
        $params = [
            'name'=> ''
        ];
        $admin = AdminUser::getDataByToken();
        if (empty($admin)) {
            return self::jsonError('账号权限不足，请检查');
        }
        
        if ($admin['role'] != AdminRole::SUPER_ADMIN) {
            $role = AdminRole::getRoleByAdmin(trim($admin['role'], ','));
            $params['id'] = explode(',', $role['menu_ids']);
        }
        $data = AdminMenuService::getList($params, ['id', 'parent', 'name', 'type', 'icon', 'route', 'mode', 'component', 'key']);
        if (empty($data)) {
            return self::jsonError('账号权限不足，请检查');
        }
        return self::jsonSuccess($data);
    }

    /**
     * 列表
     * @param array $params 参数 
     * * */
    public static function getList($params)
    {

        //检索条件
        $condition = ['AND'];
        if ($params['name']) {
            $condition[] = ['like', 'name', $params['name']];
        }
        if ($params['account']) {
            $condition[] = ['like', 'account', $params['account']];
        }
        $list = AdminUser::getDataAll($condition, $params['page'], $params['page_size'], $order_by = 'id DESC', $select = ['id', 'name', 'account', 'role', 'create_time']);
        foreach ($list['list'] as &$value) {
            $value['role_name'] = '';
            if ($value['role'] == '-1') {
                $value['role_name'] = '超级管理员';
            } else {
                $role = AdminRole::getRoleByAdmin($value['role']);
                $value['role_name'] =  $role['name'] ?? '';
            }
        }
        return $list;
    }

    /**
     * 新增
     * @param array $params 参数 
     * * */
    public static function create($params)
    {
        if (AdminUser::getDataOne(['name' => $params['name']])) {
            return self::jsonError('账号已存在');
        }
        if (empty($params['pass'])) {
            return self::jsonError('请输入密码');
        }
        if (AdminUser::create($params) == false) {
            return self::jsonError('保存失败');
        }
        return self::jsonSuccess();
    }

    /**
     * 新增
     * @param array $params 参数 
     * * */
    public static function update($params)
    {
        $condition = ['id' => $params['id']];
        unset($params['id']);
        if (AdminUser::updateData($params, $condition) === false) {
            return self::jsonError('更新失败');
        }
        return self::jsonSuccess();
    }

    /**
     * 删除
     * @param array $params 参数 
     * * */
    public static function delete($params)
    {
        $condition = ['id' => $params['id']];
        if (AdminUser::del($condition) == false) {
            return self::jsonError('删除失败');
        }
        return self::jsonSuccess();
    }

    /**
     * 导出
     * @param array $params 参数 
     * * */
    public static function Export($data)
    {
        $title = [
            'account' => '账号',
            'realname' => '真实姓名',
            'phone' => '手机号',
            'role_name' => '权限',
            'sex_name' => '性别',
        ];
        return \Yii::$app->excel->exportCsv($title, $data);
    }

    /**
     * 导入
     * @param array $params 参数 
     * * */
    public static function Import($files)
    {
        $data = \Yii::$app->excel->Import($files);
        return self::jsonSuccess();
    }

    /**
     * 详情
     * @param array $params 参数 
     * **/
    public static function detail($params)
    {
        $condition = ['id' => $params['id']];
        $data = AdminUser::getDataOne($condition, '', ['id','name', 'account', 'role']);
        return self::jsonSuccess($data);
    }
}
